package main

import (
    "fmt"
    "log"
    "spam3uk/internal/config"
    "spam3uk/internal/models"
    "spam3uk/internal/storage"
    "time"

    "gorm.io/datatypes"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func testUpsert() {
	fmt.Println("=== UPSERT功能测试 ===")

	// 加载配置
    cfg, err := config.LoadConfig("spam3uk-config.json")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.Database.Username,
		cfg.Database.Password,
		cfg.Database.Host,
		cfg.Database.Port,
		cfg.Database.Database)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 创建存储实例
	store := storage.NewMySQLStorage(db)

	// 测试数据
	testVehicle := &models.VehicleInfo{
		VehicleCategory: "performance",
		VehicleType:     "Test Sports Car",
		Make:            "Ford",
		Model:           "Test Mustang",
		Variant:         "Test GT",
		PriceFrom:       floatPtr(35000),
		PriceTo:         floatPtr(45000),
		FuelType:        "Petrol",
		EngineSize:      "5.0L V8",
		Transmission:    "Manual",
		BodyStyle:       "Coupe",
		Doors:           intPtr(2),
		Seats:           intPtr(4),
		ImageURL:        "http://test.com/mustang.jpg",
		DetailURL:       "http://test.com/mustang-details",
		Description:     "Test vehicle for UPSERT functionality verification",
        Specifications:  datatypes.JSON([]byte(`{"power": "450hp", "0_60": "4.2s", "top_speed": "250km/h"}`)),
        Features:        datatypes.JSON([]byte(`["Launch Control", "Track Mode", "Brembo Brakes"]`)),
		Availability:    "Available",
		SourcePage:      "http://test.com/source",
	}

	fmt.Println("\n1. 第一次插入测试记录...")
	err = store.UpsertVehicle(testVehicle)
	if err != nil {
		log.Fatalf("First upsert failed: %v", err)
	}
	fmt.Printf("✅ 首次插入成功，ID: %d\n", testVehicle.ID)

	// 验证插入的记录
	insertedVehicle, err := store.GetByID(testVehicle.ID)
	if err != nil {
		log.Fatalf("Failed to get inserted vehicle: %v", err)
	}
	fmt.Printf("插入记录时间: 创建=%v, 更新=%v, 抓取=%v\n",
		insertedVehicle.CreatedAt.Format("2006-01-02 15:04:05"),
		insertedVehicle.UpdatedAt.Format("2006-01-02 15:04:05"),
		insertedVehicle.ScrapedAt.Format("2006-01-02 15:04:05"))

	// 等待几秒
	fmt.Println("\n⏰ 等待3秒...")
	time.Sleep(3 * time.Second)

	fmt.Println("\n2. 更新同一记录测试...")
	// 修改一些字段来模拟数据更新
	testVehicle.VehicleType = "Updated Sports Car"
	testVehicle.PriceFrom = floatPtr(38000)
	testVehicle.PriceTo = floatPtr(48000)
	testVehicle.EngineSize = "5.2L V8"
	testVehicle.Description = "UPDATED: Test vehicle for UPSERT functionality verification"
    testVehicle.Specifications = datatypes.JSON([]byte(`{"power": "480hp", "0_60": "4.0s", "top_speed": "260km/h"}`))

	originalID := testVehicle.ID
	err = store.UpsertVehicle(testVehicle)
	if err != nil {
		log.Fatalf("Second upsert failed: %v", err)
	}
	fmt.Printf("✅ 更新成功，ID保持不变: %d\n", testVehicle.ID)

	// 验证更新的记录
	updatedVehicle, err := store.GetByID(originalID)
	if err != nil {
		log.Fatalf("Failed to get updated vehicle: %v", err)
	}
	fmt.Printf("更新记录时间: 创建=%v, 更新=%v, 抓取=%v\n",
		updatedVehicle.CreatedAt.Format("2006-01-02 15:04:05"),
		updatedVehicle.UpdatedAt.Format("2006-01-02 15:04:05"),
		updatedVehicle.ScrapedAt.Format("2006-01-02 15:04:05"))

	// 验证时间字段逻辑
	fmt.Println("\n3. 验证时间字段逻辑...")
	if updatedVehicle.CreatedAt.Equal(insertedVehicle.CreatedAt) {
		fmt.Println("✅ created_at 保持不变")
	} else {
		fmt.Println("❌ created_at 不应该改变")
	}

	if updatedVehicle.UpdatedAt.After(insertedVehicle.UpdatedAt) {
		fmt.Println("✅ updated_at 已更新")
	} else {
		fmt.Println("❌ updated_at 应该更新")
	}

	if updatedVehicle.ScrapedAt.After(insertedVehicle.ScrapedAt) {
		fmt.Println("✅ scraped_at 已更新")
	} else {
		fmt.Println("❌ scraped_at 应该更新")
	}

	// 验证业务字段更新
	fmt.Println("\n4. 验证业务字段更新...")
	if updatedVehicle.VehicleType == "Updated Sports Car" {
		fmt.Println("✅ vehicle_type 已更新")
	} else {
		fmt.Println("❌ vehicle_type 更新失败")
	}

	if *updatedVehicle.PriceFrom == 38000 {
		fmt.Println("✅ price_from 已更新")
	} else {
		fmt.Println("❌ price_from 更新失败")
	}

	// 检查是否有重复记录
	fmt.Println("\n5. 检查重复记录...")
	var count int64
	db.Model(&models.VehicleInfo{}).Where("make = ? AND model = ? AND variant = ?",
		"Ford", "Test Mustang", "Test GT").Count(&count)
	if count == 1 {
		fmt.Println("✅ 没有重复记录")
	} else {
		fmt.Printf("❌ 发现 %d 条重复记录\n", count)
	}

	// 清理测试数据
	fmt.Println("\n6. 清理测试数据...")
	err = store.Delete(originalID)
	if err != nil {
		log.Printf("Failed to delete test data: %v", err)
	} else {
		fmt.Println("✅ 测试数据已清理")
	}

	fmt.Println("\n=== UPSERT功能测试完成 ===")
}

func floatPtr(f float64) *float64 {
	return &f
}

func intPtr(i int) *int {
	return &i
}
